package com.example.service.impl;

import com.example.service.RequestAttrService;
import com.example.util.CustomRequestContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.FutureTask;

/**
 * @author long
 * @date 2025/6/20 11:17
 */
@Service
public class RequestAttrServiceImpl implements RequestAttrService {

//    @Resource
    private Executor testTaskExecutor;

    @Override
    public String getRequestAttr() throws Exception {
        // 场景1：正常获取请求属性
//        return requestAttr();

        // 场景2：通过new Thread方法异步获取
//        FutureTask<String> futureTask = new FutureTask<>(this::requestAttr);
//        new Thread(futureTask).start();
//        return futureTask.get();

        // 场景3：通过线程池获取
        CompletableFuture<String> future = CompletableFuture.supplyAsync(this::requestAttr,testTaskExecutor);
        return future.get();
    }

    private String requestAttr(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        if(Objects.isNull(servletRequestAttributes)){
            servletRequestAttributes = (ServletRequestAttributes)CustomRequestContextHolder.getRequestAttributes();
            if(servletRequestAttributes == null){
                return "none";
            }
        }
        HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();
        return httpServletRequest.getHeader("username");
    }

}
